package com.c5p1ng.route.config;

import com.c5p1ng.route.RouteProperties;
import com.c5p1ng.route.ribbon.NacosLoadBalancerRule;
import com.c5p1ng.route.util.SpringContextUtil;
import com.netflix.loadbalancer.IRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 路由自动配置类
 *
 * @author csp
 **/
@Configuration
@EnableConfigurationProperties(RouteProperties.class)
@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.enabled", matchIfMissing = true)
public class RouteAutoConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(RouteAutoConfiguration.class);

    @Bean
    @ConditionalOnProperty(prefix = "route", value = "enable", havingValue = "true")
    public IRule getRibbonRule() {
        LOGGER.info("开启自定义路由!!");
        return new NacosLoadBalancerRule();
    }

    @Resource
    ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        SpringContextUtil.setContext(applicationContext);
    }
}
